<template>
  <div>
    <!-- 视频上传组件 -->
    <el-upload
      class="avatar-uploader el-upload--text"
      :action="baseUrl"
      :show-file-list="false"
      :on-success="handleVideoSuccess"
      :before-upload="beforeUploadVideo"
      :on-progress="uploadVideoProcess"
      :headers="headers"
    >
      <!-- 视频预览 -->
      <video
        v-if="promotionVideoUrl && promotionVideoUrl !== '' && !videoFlag"
        :src="promotionVideoUrl"
        class="avatar"
        controls
      >
        您的浏览器不支持视频播放
      </video>
      
      <!-- 上传按钮（未上传时） -->
      <i
        v-if="(!promotionVideoUrl || promotionVideoUrl === '') && !videoFlag"
        class="el-icon-plus avatar-uploader-icon"
      ></i>
      
      <!-- 上传进度条 -->
      <el-progress
        v-if="videoFlag"
        type="circle"
        :percentage="videoUploadPercent"
        style="margin-top: 30px;"
      ></el-progress>
    </el-upload>
    
    <!-- 删除按钮 -->
    <el-button 
      @click="handleDelete" 
      v-if="promotionVideoUrl && !videoFlag" 
      type="danger"
    >
      删除视频
    </el-button>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";

export default {
  name: "VideoUpload",
  model: {
    prop: "value",
    event: "input"
  },
  props: {
    value: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      promotionVideoUrl: "", // 视频完整地址（用于预览）
      videoFlag: false, // 上传状态标记（true：上传中）
      videoUploadPercent: 0, // 上传进度百分比
      baseUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传接口地址
      headers: {
        Authorization: "Bearer " + getToken() // 携带Token认证
      }
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          // 拼接完整视频地址用于预览
          this.promotionVideoUrl = process.env.VUE_APP_BASE_API + val;
        } else {
          this.promotionVideoUrl = null;
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 删除视频
    handleDelete() {
      this.promotionVideoUrl = null;
      this.$emit("input", ""); // 通知父组件清空值
    },
    
    // 上传前验证视频格式
    beforeUploadVideo(file) {
      const validExts = ['mp4', 'ogg', 'flv', 'avi', 'wmv', 'rmvb'];
      const fileExt = file.name.split('.').pop()?.toLowerCase();
      
      // 验证文件后缀
      if (!validExts.includes(fileExt)) {
        this.$message.error('请上传 mp4/ogg/flv/avi/wmv/rmvb 格式的视频');
        return false;
      }
      
      // 验证MIME类型
      const validTypes = [
        'video/mp4',
        'video/ogg',
        'video/flv',
        'video/avi',
        'video/wmv',
        'video/rmvb'
      ];
      if (!validTypes.includes(file.type)) {
        this.$message.error('请上传正确的视频格式');
        return false;
      }
      
      return true; // 允许上传
    },
    
    // 上传进度更新
    uploadVideoProcess(event) {
      this.videoFlag = true;
      this.videoUploadPercent = Math.floor(event.percent); // 取整数百分比
    },
    
    // 上传成功回调
    handleVideoSuccess(res) {
      this.videoFlag = false;
      this.videoUploadPercent = 0;
      
      if (res.code === 200) {
        // 拼接完整地址用于预览
        this.promotionVideoUrl = process.env.VUE_APP_BASE_API + res.url;
        // 向父组件传递相对路径
        this.$emit("input", res.url);
      } else {
        this.$message.error('视频上传失败，请重新上传！');
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.avatar-uploader-icon {
  border: 1px dashed #d9d9d9 !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px !important;
  position: relative !important;
  overflow: hidden !important;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff !important;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 300px;
  height: 178px;
  display: block;
  object-fit: contain; // 视频保持比例
}
</style>